package com.erp.common.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.common.select.beans.SelectDelegate;
import com.erp.framework.util.CommonUtil;
import com.erp.app.common.ProjectConstants;

public class BBALoginAction extends Action
{

	public static final int failedLoginCount = 3;
	
    public ActionForward perform(ActionMapping mapping,
								 ActionForm formIn,
								 HttpServletRequest request,
								 HttpServletResponse response)
		throws ServletException
    {

		HttpSession session = request.getSession(false);
		ActionErrors errors = new ActionErrors();
    	ActionForward actionForward = new ActionForward(mapping.getInput());


		BBALoginForm form = (BBALoginForm) formIn;

		// Action: Login
		if ("Login".equals(request.getParameter("btn_login"))) {
			String userId = CommonUtil.nullToString(form.getUserId());
			String password = CommonUtil.nullToString(form.getPassword());
			
			SelectDelegate sdg = new SelectDelegate();
			
			String query = "select count(*)"
				+ " from t_user "
				+ " where user_code = '"+userId+"'"
				+ " and password = '"+password+"'";
			
			String rslt = String.valueOf(sdg.selectOneValue(query));
			if (CommonUtil.isValidInteger(rslt)) {
				int count = Integer.parseInt(rslt);
				if (count > 0) {
					session.setAttribute(ProjectConstants.SESSION_BBA_LOGIN_SUCCESS, ProjectConstants.GENERIC_YES);
					actionForward = mapping.findForward("success");
				} else {
					actionForward = handleFailedLogin(mapping, formIn, request, errors);
				}
			} else {
				actionForward = handleFailedLogin(mapping, formIn, request, errors);
			}
		}
		
		saveErrors(request, errors);
		saveToken(request);
		
		return actionForward;
    }
    

	protected ActionForward handleFailedLogin(ActionMapping mapping,
											  ActionForm formIn,
											  HttpServletRequest request,
											  ActionErrors errors) {

		ActionForward actionForward = new ActionForward(mapping.getInput());
		HttpSession session = request.getSession(false);
		BBALoginForm form = (BBALoginForm) formIn;

		int count = 1;
		try {
			count = Integer.parseInt(form.getNoOfTries());
		} catch (Exception e) {
			count = 1;
		}

		if ( count >= failedLoginCount ){
			form.setNoOfTries("0");
			actionForward = mapping.findForward("loginError");
		} else {
			form.setNoOfTries(String.valueOf(count+1));
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.msg.li", "Invalid User ID / Password"));
		}

		return actionForward;
	}

}
